﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HousingInfo.Library;
using System.IO;

namespace NEWS.Admin
{
    public partial class EditNewsHouses : System.Web.UI.Page
    {
        private static NewsHouseBO newsHouseBO;
        private static LocationAdvertisementBO boqc;
        private static LocationAdvertisementDetailBO qcdetailbo;
        private static string option = null;
        private static OptionBO optionbo;
        private static string _fileImageName;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //                    <asp:CollapsiblePanelExtender ExpandedImage="img/an.png"
                //CollapsedImage="img/hien.png" ImageControlID="imgBackgroundEmployeeDetail" SuppressPostBack="true" Collapsed="false" ID="CollapsiblePanelExtender1" TargetControlID="pn_content_detail" ExpandControlID="pn_title_detail" CollapseControlID="pn_title_detail" runat="server">
                //    </asp:CollapsiblePanelExtender>
                //<asp:RequiredFieldValidator ID="RequiredFieldValidator4" Display="None" runat="server" ControlToValidate="txtwidth"
                //                        ErrorMessage="<b>Lỗi nhập liệu</b><br />Yêu cầu nhập chiều rộng"></asp:RequiredFieldValidator>
                //                <asp:ValidatorCalloutExtender ID="RequiredFieldValidator4_ValidatorCalloutExtender" 
                //                    runat="server" TargetControlID="RequiredFieldValidator4">
                //                </asp:ValidatorCalloutExtender>
                //                <asp:RegularExpressionValidator Display="None" ID="RegularExpressionValidator5" runat="server" ControlToValidate="txtwidth"
                //                    ErrorMessage="Diện tích phải kiểu số" 
                //                    ValidationExpression="^\d+$"></asp:RegularExpressionValidator> 
                                
                //                <asp:ValidatorCalloutExtender ID="RegularExpressionValidator5_ValidatorCalloutExtender" 
                //                    runat="server" Enabled="True" TargetControlID="RegularExpressionValidator5">
                //                </asp:ValidatorCalloutExtender>

                //lay thong tin lien he - chua login nen mac dinh la admin
                //string cvb = "," + "," + "," + ",";
                //var okokok = cvb.Split(',');
                
                try
                {
                    UserBO userBO = UserBO.GetUserBO("admin");
                    txtcontactname.Text = userBO.FullName;
                    txtcontactaddress.Text = userBO.Address;
                    txtcontactEmail.Text = userBO.Email;
                    txtcontactphone.Text = userBO.TelePhone;
                }
                catch { }
                //end
                getHouseType();
                getAreas();
                getCurrency();
                getCategoryHouse();
            }
        }
        private void getHouseType()
        {
            try
            {
                var housingType = HousingTypeInfo.GetHousingTypeInfo();
                dlhousetype.DataSource = housingType;
                dlhousetype.DataBind();
            }
            catch{}
        }

        private void getCategoryHouse()
        {
            try
            {
                var categoryHouse = CategoryInfo.GetCategoryInfo_BySingle(true, false, false, false, true);
                dlcategoryhouse.DataSource = categoryHouse;
                dlcategoryhouse.DataBind();
            }
            catch { }
        }

        private void getAreas()
        {
            try
            {
                var areas = AreaInfo.GetAreaInfo();
                if (areas != null)
                {
                    dlareas.DataSource = areas;
                    dlareas.DataBind();
                    //lay danh sach khu vuc con
                    var areaId = areas[0].Key.ToString();
                    getAreaDetailWithAreaId(areaId);
                }
            }
            catch{}
        }
        private void getAreaDetailWithAreaId(string areaId)
        {
            try
            {
                var areadetailList = AreaDetailInfo.GetAreaDetailInfo(int.Parse(areaId));
                dlareadetail.DataSource = areadetailList;
                dlareadetail.DataBind();
            }
            catch (Exception)
            {

            }

        }

        private void getCurrency()
        {
            try
            {
                var currenyInfo = CurrencyInfo.GetCurrencyInfo();
                dlcurrency.DataSource = currenyInfo;
                dlcurrency.DataBind();
            }
            catch
            { }
        }

        private void getLocation()
        {
            try
            {
                var locationInfo = LocationAdvertisementInfo.GetLocationAdvertisementInfo();
                dlkhuvuc_qc.DataSource = locationInfo;
                dlkhuvuc_qc.DataBind();
                changeChiTietQuangCao();
            }
            catch
            { }
        }

        protected void dlareas_SelectedIndexChanged(object sender, EventArgs e)
        {
            var areaId = dlareas.SelectedValue;
            getAreaDetailWithAreaId(areaId);
        }

        protected void btndangtin_Click(object sender, EventArgs e)
        {
            newsHouseBO = NewsHouseBO.NewNewsHouseBO();
            newsHouseBO.UserName = "admin";
            newsHouseBO.AreaDetailID = Convert.ToInt32(dlareadetail.SelectedValue);
            newsHouseBO.CategoryID = Convert.ToInt32(dlcategoryhouse.SelectedValue);
            newsHouseBO.CurrencyID = Convert.ToInt32(dlcurrency.SelectedValue);
            newsHouseBO.HousingTypeID = Convert.ToInt32(dlhousetype.SelectedValue);
            if (rdsodo.Checked == true)
            {
                newsHouseBO.Documents = "Sổ Đỏ";
            }
            else if (rdsohong.Checked == true)
            {
                newsHouseBO.Documents = "Sổ Hồng";
            }
            else newsHouseBO.Documents = "Giấy Tay";
            newsHouseBO.SurfaceAreaWidth = Convert.ToInt32(txtwidth.Text);
            newsHouseBO.SurfaceAreaHeight = Convert.ToInt32(txtheight.Text);
            newsHouseBO.SupM = cbmv.Checked;
            newsHouseBO.HousesAddress = txtaddress.Text;
            newsHouseBO.Direction = dlDirection.SelectedValue;
            newsHouseBO.Price = decimal.Parse(txtprice.Text);
            newsHouseBO.IsNegotiation = cbthuongluong.Checked;
            newsHouseBO.CreatedDate = DateTime.Now;
            newsHouseBO.PostDate = DateTime.Now;
            newsHouseBO.UpdatedDate = DateTime.Now;
            newsHouseBO.ExpireDate = DateTime.Now.AddDays(double.Parse(dltimepost.SelectedValue));
            newsHouseBO.Title = txttitle.Text;
            newsHouseBO.NewsContent = txtmota.Text;
            //upload anh
            if (upload_one_image.FileName.Length > 0)
            {
                postImage(upload_one_image);
            }
            newsHouseBO.ViewCount = 0;
            newsHouseBO.IsExtension = false;
            newsHouseBO.NumExtension = 0;
            newsHouseBO.IsPremium = false;
            newsHouseBO.IsAdvertisement = false;
            if (pn_quangcao.Visible == true)
            {
                if (upload_image_qc.FileName.Length > 0)
                {
                    postImageQuangCao();
                    newsHouseBO.IsPremium = true;
                    newsHouseBO.IsAdvertisement = true;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn ảnh quảng cáo !!!')", true);
                    upload_image_qc.Focus();
                    return;
                }
            }            
            newsHouseBO.IsActive = cbkichhoat.Checked;
            if (cbkichhoat.Checked == true)
                newsHouseBO.ActiveDate = DateTime.Now;
            newsHouseBO.NumPost = 0;
            newsHouseBO.IsContact = true;
            newsHouseBO.ContactName = txtcontactname.Text;
            newsHouseBO.ContactAddress = txtcontactaddress.Text;
            newsHouseBO.ContactEmail = txtcontactEmail.Text;
            newsHouseBO.ContactPhone = txtcontactphone.Text;
            string addons = "", interiorAmenities = "", socialCulture = "";
            addons += txtbuidyear.Text + ",";
            addons += txtnhatam_vesinh.Text + ",";
            addons += txtso_phongngu.Text + ",";
            addons += cbnuocmay.Checked.ToString() + ",";
            addons += cbdonghodien.Checked.ToString() + ",";
            addons += txtduongtruocnha.Text;
            newsHouseBO.Addons = addons;
            interiorAmenities += cbthangmay.Checked.ToString() + ",";
            interiorAmenities += cbbaove.Checked.ToString() + ",";
            interiorAmenities += cbdauoto.Checked.ToString() + ",";
            interiorAmenities += cbsanvuon.Checked.ToString() + ",";
            interiorAmenities += cbdieuhoa.Checked.ToString() + ",";
            interiorAmenities += cbsanthuong.Checked.ToString() + ",";
            interiorAmenities += cbdienthoai.Checked.ToString() + ",";
            interiorAmenities += cbhoboi.Checked.ToString() + ",";
            interiorAmenities += cbnhabep.Checked.ToString() + ",";
            interiorAmenities += cbgaraoto.Checked.ToString() + ",";
            interiorAmenities += cbphongkhach.Checked.ToString();
            newsHouseBO.InteriorAmenities = interiorAmenities;
            socialCulture += cbcongvien.Checked.ToString() + ",";
            socialCulture += cbtrungtam_giaitri.Checked.ToString() + ",";
            socialCulture += cbmaugiao.Checked.ToString() + ",";
            socialCulture += cbtrungtam_thuongmai.Checked.ToString() + ",";
            socialCulture += cbdh_cd.Checked.ToString() + ",";
            socialCulture += cbbenhvien.Checked.ToString() + ",";
            socialCulture += cbcapba.Checked.ToString() + ",";
            socialCulture += cbcho.Checked.ToString() + ",";
            socialCulture += cbcaphai.Checked.ToString() + ",";
            socialCulture += cbkinhdoanh.Checked.ToString() + ",";
            socialCulture += cbcapmot.Checked.ToString() + ",";
            socialCulture += cbkhudantri.Checked.ToString();
            newsHouseBO.SocialCulture = socialCulture;
        }

        private void postImage(FileUpload filename)
        {
            //try
            //{
            //    if (filename.HasFile)
            //    {
            //        if (filename.FileBytes.Length < 1048576)
            //        {
            //            _fileImageName = filename.FileName.Replace(" ", "_");
                        
            //            string formatFile = Path.GetExtension(_fileImageName);
            //            //kiem tra dinh dang cho phep upload
            //            if (formatFile.Equals(".jpg") || formatFile.Equals(".gif") || formatFile.Equals(".png") || formatFile.Equals(".JPG") || formatFile.Equals(".GIF") || formatFile.Equals(".PNG"))
            //            {
            //                //kiem tra file da ton tai
            //                string filePath = HttpContext.Current.Server.MapPath("~/Admin/VanBan/" + _fileImageName);
            //                if (File.Exists(filePath))
            //                {
            //                    //neu ton tai thi doi ten
            //                    _fileImageName = ImageFileName(_fileImageName);
            //                }
            //                //thuc hien luu file
            //                try
            //                {
            //                    FileUpload_Doccument.SaveAs(Server.MapPath("~/Admin/VanBan/" + _fileImageName));
            //                    message.Text = "Upload thành công";
            //                    deleteExitsImage(txtlink.Text);
            //                    txtlink.Text = _fileImageName;
            //                    btnthaydoivanban.Text = "Thay Đổi Văn Bản";
            //                    btndownload.Visible = true;
            //                    pn_upload.Visible = false;
            //                }
            //                catch (Exception)
            //                {
            //                    message.Text = "Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.";
            //                }
            //            }
            //            else
            //            {
            //                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
            //                                                    "alert('Chỉ được upload các định dạng văn bản (.doc , .pdf)')", true);
            //            }
            //        }
            //        else
            //        {
            //            message.Text = "Kích thước văn bản không quá 3MB";
            //        }
            //    }
            //    else
            //    {
            //        message.Text = "Chưa chọn file văn bản. !";
            //    }
            //}
            //catch {}
        }

        private void postImageQuangCao()
        {

        }

        protected void btntrove_Click(object sender, EventArgs e)
        {

        }

        protected void lbtdangtin_qc_Click(object sender, EventArgs e)
        {
            pn_quangcao.Visible = true;
            getLocation();
        }

        protected void dlkhuvuc_qc_SelectedIndexChanged(object sender, EventArgs e)
        {
            changeChiTietQuangCao();
        }

        private void changeChiTietQuangCao()
        {
            option = null;
            string vitridaco = "";
            string vitrichuaco = "";
            lblthongtinquangcao.Text = "";
            int idqc;
            idqc = Convert.ToInt32(dlkhuvuc_qc.SelectedValue);
            if (idqc == 1)
            {
                option = "SoViTriQCTren";
                lblthongtinquangcao.Text = "Chi tiết:<br />+ Dưới Banner của trang web<br />+Tổng cộng có ";
            }
            else if (idqc == 2)
            {
                option = "SoViTriQCTrai";
                lblthongtinquangcao.Text = "Chi tiết:<br />+ Cột bên trái của trang web<br />+Tổng cộng có ";
            }
            else if (idqc == 3)
            {
                option = "SoViTriQCPhai";
                lblthongtinquangcao.Text = "Chi tiết:<br />+ Cột bên phải của trang web<br />+Tổng cộng có ";
            }
            dlchitiet.Items.Clear();
            try
            {
                optionbo = OptionBO.GetNameOptionBO(option);
            }
            catch
            {
                optionbo = null;
            }
            if (optionbo != null)
            {
                lblthongtinquangcao.Text += "<span>" + Convert.ToInt32(optionbo.OptionValue) + "</span>" + " vị trí cho phép đăng quảng cáo";
                boqc = LocationAdvertisementBO.GetLocationAdvertisementBO(idqc);
                for (int i = 1; i <= Convert.ToInt32(optionbo.OptionValue); i++)
                {
                    try
                    {
                        qcdetailbo = boqc.LocationAdvertisementDetailBOList.Single(a => a.LocationInWeb == i.ToString());
                    }
                    catch
                    {
                        qcdetailbo = null;
                    }
                    if (qcdetailbo == null)
                    {
                        dlchitiet.Items.Add(i.ToString());
                        if (vitrichuaco == "")
                        {
                            vitrichuaco = i.ToString();
                        }
                        else vitrichuaco += ", " + i.ToString();
                    }
                    else
                    {
                        if (vitridaco == "")
                        {
                            vitridaco += i.ToString() + " <a class='xemtindaquangcao' href='#'>Xem</a>";
                        }
                        else vitridaco += ", " + i.ToString() + " <a class='xemtindaquangcao' href='#'>Xem</a>";
                    }
                }
                lblthongtinquangcao.Text += "<br />+Các Vị trí đã được đăng tin quảng cáo: " + vitridaco + "<br />+Các vị trí còn trống: " + vitrichuaco;
            }
        }

        protected void lbtaddimage_Click(object sender, EventArgs e)
        {
            pn_Extract_Image.Visible = true;
        }

        protected void lbt_huy_extract_image1_Click(object sender, EventArgs e)
        {
            pn_Extract_Image.Visible = false;
        }

        protected void btndong_Click(object sender, EventArgs e)
        {
            pn_quangcao.Visible = false;
        }

        protected void btnketthuc_qc_Click(object sender, EventArgs e)
        {
            //tin nay dang dang ky quang cao - thuc hien thoi quang cao
        }
    }
}
